import router from './index'

// 自动引入所有 views 下的 vue 文件
const modules = import.meta.glob('/src/views/**/*.vue')

const STATIC_PATHS = ['/', '/login', '/register']

export function addDynamicRoutes(menuList) {
  menuList.forEach(menu => {
    if (
      menu.type === 2 &&
      menu.component &&
      !STATIC_PATHS.includes(menu.path)
    ) {
      const matchPath = `/src/views/${menu.component}.vue`
      const component = modules[matchPath]

      if (!component) {
        console.warn(`[动态路由失败] 组件未找到: ${matchPath}`)
      } else {
        const dynamicPath = menu.path.startsWith('/')
          ? menu.path.slice(1)
          : menu.path

        router.addRoute('layout', {
          path: dynamicPath,
          component,
          meta: {
            title: menu.title || '',
            requiresAuth: true
          }
        })

        console.log('[动态路由注册]', dynamicPath, '=>', matchPath)
      }
    }

    // 递归处理子菜单
    if (Array.isArray(menu.children) && menu.children.length > 0) {
      addDynamicRoutes(menu.children)
    }
  })
}
